#include <QStringList>

#include "Indicator.h"
#include "Csv.h"

static inline void
setInvalid(double *d, int start, int num)
{
   while(start < num)
   {
      d[start++] = DBL_MIN;
   }
}

bool
Indicator::compute(const Ohlc &ohlc, QList<Line> &lines)
{
   // First parse the indicator definition
   Csv csv;
   QStringList params;
   if(!csv.parse(definition_.toAscii().data(), params)) return false;

   if(params.size() == 0) return false;

   // The first parameter is the name
   if(0 == params.at(0).compare("macd", Qt::CaseInsensitive))
   {
   }
   else if(0 == params.at(0).compare("rsi", Qt::CaseInsensitive))
   {
   }
   else if(0 == params.at(0).compare("ma", Qt::CaseInsensitive))
   {
      if(params.size() < 2) return false;

      bool b;
      int period = params.at(1).toInt(&b);
      if(!b) return false;

      // Append a new line to the list, and remove it in error code paths
      lines.append(Line());
      Line &line = lines.last();
      line.ohlc().vals.reserve(ohlc.size());
      int outStart, outNum;
      double *data = line.ohlc().vals.data();
      TA_RetCode rc = TA_MA(0, ohlc.size()-1, ohlc.c.data(), period, TA_MAType_SMA, &outStart, &outNum, data);
      if(rc != 0) {lines.removeLast(); return false;}

      // The lines must be aligned with each other
      memmove(data + outStart, data, outNum*sizeof(double));

      // Make all values that were not computed invalid
      setInvalid(data, 0, outStart);

      line.setLabel("MA (" + QString::number(period) + ")");

      lines.append(line);
   }

   return true;
}